﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Transactions;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using SalesSys.BLL.Sales;
using SalesSys.Service.Sales;
using SalesSys.Comm.Utility;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 客户经理操作
    /// </summary>
    [RoutePrefix("api/ClientManager")]
    public class ClientManagerController : BaseApiController
    {
        OrderBLL orderBll = BllFactory.GetBll<OrderBLL>();
        private IDirectSale SaleSvc = new SalesSvc();
        CustomerBLL entityBLL = BLL.BllFactory.GetBll<CustomerBLL>();
        private EmployeeBLL employeeBLL = BllFactory.GetBll<EmployeeBLL>();
        private DistrictBLL districtBLL = BllFactory.GetBll<DistrictBLL>();
        private CustomerBalanceBLL customerBalanceBLL = new CustomerBalanceBLL();
        private CustomerContactBLL customerContactBLL = BLL.BllFactory.GetBll<CustomerContactBLL>();
        private AccountantContactBLL austomerContactBLL = BLL.BllFactory.GetBll<AccountantContactBLL>();
        private CustomerOperateRecordBLL customerOperateRecordBLL = BLL.BllFactory.GetBll<CustomerOperateRecordBLL>();
        private PaymentInfoBLL paymentInfoBLL = BllFactory.GetBll<PaymentInfoBLL>();

        /// <summary>
        /// 获取客户经理客户
        /// </summary>
        /// <param name="name">客户名称</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        [Route("Customer")]
        public ViewDtos<Customer> GetCustomer(string name = null, int page = 1, int rows = 10)
        {
            KeyValuePair<int, IEnumerable<Customer>> data;
            data = customerBalanceBLL.GetMyAllCustomers(name, ClientHelper.ClientInfo.Id, page, rows);
            var dto = ViewDto.CreateList(data.Value);
            dto.Page = page;
            dto.Rows = rows;
            dto.Total = data.Key;
            return dto;
        }

        /// <summary>
        /// 新增客户
        /// </summary>
        /// <param name="customer">客户实体</param>
        [Route("AddCustomer")]
        public void AddCustomer(Customer customer)
        {
            using (var tran = new TransactionScope())
            {
                var nowCust = entityBLL.ExistByName(customer);
                if (nowCust != null && nowCust.IsDelete == false && nowCust.ApprovalState != ApprovalState.Disagree)
                {
                    throw new ApiArgException("客户名称已报备，如未找到，可能是正在处理中，可稍后联系客服确认");
                }
                customer.CreateTime = DateTime.Now;
                if (customer.District != null)
                {
                    customer.District = districtBLL.Details(customer.District.Id);

                }
                customer.ApprovalState = ApprovalState.Pending;
                customer.CreditScore = 80;
                if (customer.ClientManager == null)
                {
                    customer.ClientManager = employeeBLL.Details(ClientHelper.ClientInfo.Id);
                }
                // entityBLL.AddCashAccountIfNon(customer);

                entityBLL.Create(customer);
                SendMsg(customer);
                //添加普通客户联系人
                List<CustomerContact> customerContacts = customer.CustomerContacts.ToList();
                if (customerContacts.Count > 0)
                {
                    foreach (var item in customerContacts)
                    {
                        item.CustomerId = customer.Id;
                        customerContactBLL.Create(item);
                    }
                }
                //添加财务联系人
                List<AccountantContact> accountantContacts = customer.AccountantContacts.ToList();
                if (accountantContacts.Count > 0)
                {
                    foreach (var item in accountantContacts)
                    {
                        item.CustomerId = customer.Id;
                        austomerContactBLL.Create(item);
                    }
                }
                //添加客户操作记录表
                CustomerOperateRecord operateRecord = new CustomerOperateRecord();
                operateRecord.OperatorAction = "Create";
                operateRecord.CustomerId = customer.Id;
                operateRecord.BeforeContent = "";
                customer.District = new District();
                customer.District.Children = null;
                customer.District.Parent = null;
                operateRecord.AfterContent = SalesSys.Comm.Utility.SimpleJson.Serializer(customer);
                operateRecord.OperatorTime = DateTime.Now;
                operateRecord.OperatorId = ClientHelper.ClientInfo.Id;
                operateRecord.Id = Guid.NewGuid();
                customerOperateRecordBLL.Create(operateRecord);
                //添加客户余额表
                CustomerBalance customerBalance = new CustomerBalance();
                customerBalance.CustomerId = customer.Id;
                customerBalance.Balance = 0;
                customerBalance.EmployeeId = ClientHelper.ClientInfo.Id;
                customerBalance.Id = Guid.NewGuid();
                customerBalanceBLL.Create(customerBalance);
                tran.Complete();
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="cst"></param>
        private void SendMsg(Customer cst)
        {
            var nb = new NoticeInfoBLL();
            var str = string.Format("{0:M/d HH:mm} [客户报备申请]{1}:{2}", DateTime.Now, ClientHelper.ClientInfo.Name, cst.Name);
            nb.SendMsg(str, default(Guid), new[] { RolesConst.Service });
        }

        /// <summary>
        /// 我的计划单
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="state">订单状态</param>
        /// <param name="keyword">模糊搜索</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>计划单列表</returns>
        [Route("OrderList")]
        public ViewDto<IEnumerable<Order>> GetOrderList(int page = 1, int rows = 10, OrderState? state = null, string keyword = null, DateTime? startTime = null, DateTime? endTime = null)
        {
            var empId = ClientHelper.ClientInfo.Id;
            var bll = BllFactory.GetBll<OrderBLL>();
            var re = bll.OrderList(keyword, empId, null, state, startTime, endTime, page, rows);
            var dto = new ViewDto<IEnumerable<Order>>();
            dto.Data = re.Item2;
            dto.Total = re.Item1;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 我的锁价单列表
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="state">状态</param>
        /// <param name="keyword">模糊查询</param>
        [Route("LockOrderList")]
        public ViewDto<IEnumerable<LockOrder>> GetLockOrderList(int page, int rows, OrderState? state = null, string keyword = null)
        {
            var empId = ClientHelper.ClientInfo.Id;
            var bll = BllFactory.GetBll<LockOrderBLL>();
            var re = bll.Select(empId, keyword, state, new QueryInfo { Page = page, Rows = rows });
            var dto = new ViewDto<IEnumerable<LockOrder>>();
            dto.Data = re.Value;
            dto.Total = re.Key;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }


        /// <summary>
        /// 获取报款列表
        /// </summary>
        /// <param name="customerName">客户名称（模糊查询）</param>
        /// <param name="state">审批状态</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns>报款信息列表</returns>
        [Route("PaymentInfo")]
        public ViewDtos<PaymentInfo> GetPaymentInfo(string customerName = null, FinaceApprovalState? state = null, int page = 1, int rows = 10)
        {
            ViewDtos<PaymentInfo> dto = new ViewDtos<PaymentInfo>();

            var data = paymentInfoBLL.Select(customerName, state, "", GetRequestQuery(), ClientHelper.ClientInfo.Id);
            dto.Data = data.Value;
            dto.Total = data.Key;

            dto.Rows = rows;
            dto.Page = page;
            return dto;
        }

        /// <summary>
        /// 申请报款
        /// </summary>
        /// <param name="payInfo">付款实体</param>
        [Route("ApplyPaymentInfo")]
        public void ApplyPaymentInfo(PaymentInfo payInfo)
        {
            var accBll = new AccountBLL();
            payInfo.Account = accBll.Details(payInfo.AccountId);
            if (payInfo.Account.IsCash && string.IsNullOrWhiteSpace(payInfo.Remark))
                throw new ApiArgException("私户付款，请备注打卡账号后四位。");
            payInfo.CustomerAgent = new EmployeeBLL().Details(ClientHelper.ClientInfo.Id);
            payInfo.State = FinaceApprovalState.ApprovePass;
            payInfo.CreateTime = DateTime.Now;
            payInfo.PaymentTime = payInfo.PaymentTime;
            payInfo.Customer = payInfo.Account.Customer;
            payInfo.PaymentStatus = PaymentStatus.Payment;
            paymentInfoBLL.Create(payInfo);
            SendMsg(payInfo);
        }

        /// <summary>
        /// 发送提醒
        /// </summary>
        /// <param name="payInfo"></param>
        private void SendMsg(PaymentInfo payInfo)
        {
            var nb = new NoticeInfoBLL();
            var str = string.Format("{0:M/d HH:mm} [报款申请]{3}: {1}{2}", DateTime.Now, payInfo.Account.Name, payInfo.Sum.ToString("C"), ClientHelper.ClientInfo.Name);
            nb.SendMsg(str, default(Guid), new[] { RolesConst.FinancialStaff });
        }

        /// <summary>
        /// 申请退款
        /// </summary>
        /// <param name="AccountId">账户编号</param>
        [Route("ApplyRefund")]
        public IResultState ApplyRefund(Guid AccountId)
        {
            var accBll = new AccountBLL();
            var payInfo = new PaymentInfo();
            payInfo.Account = accBll.Details(AccountId);
            payInfo.CustomerAgent = new EmployeeBLL().Details(ClientHelper.ClientInfo.Id);
            if (paymentInfoBLL.CheckTKExecuting(AccountId, payInfo.Account.Customer.Id, payInfo.CustomerAgent.Id, PaymentStatus.Refund))
            {
                return ReState.ArgError.Create("退款审批不能重复提交");
            }

            payInfo.Sum = customerBalanceBLL.GetAccountAmount(payInfo.Account.Customer.Id, ClientHelper.ClientInfo.Id, AccountId);//payInfo.Account.Amount;
            payInfo.State = FinaceApprovalState.Executing;
            payInfo.CreateTime = DateTime.Now;
            payInfo.Customer = payInfo.Account.Customer;
            payInfo.PaymentStatus = PaymentStatus.Refund;
            //payInfo.Sum = payInfo.Account.Amount;
            var financeBLL = new FinanceBLL();
            using (var tran = new TransactionScope())
            {
                paymentInfoBLL.Create(payInfo);
                financeBLL.RefundApproval(payInfo.Id, payInfo.Sum, ClientHelper.ClientInfo);
                tran.Complete();
            }
            return ReState.Success.Create("已提交退款申请");

        }

        /// <summary>
        /// 获取客户经理可用客户, Ajax请求时使用
        /// </summary>
        /// <param name="name">客户名称</param>
        /// <returns>客户列表（数组）</returns>
        [Route("GetCustomer")]
        public Customer[] GetCustomer(string name = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                var data = customerBalanceBLL.GetMyCustomers(name, ClientHelper.ClientInfo.Id, 1, 9999999).Value.ToArray();
                return data;
            }
            else
            {
                var data = entityBLL.GetList(p => (p.Name.Contains(name) || p.ShortName.Contains(name)) && p.ApprovalState == ApprovalState.Agree && p.IsDelete == false);
                return data;
            }

        }
    }
}
